﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using ThoughtWorks.QRCode.Codec;
using RestSharp;
using ImageProcessor;
using ImageProcessor.Imaging.Formats;

namespace heyirunde.variable
{
    public class QrCodeHelper
    {
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="text">字符串（生成二维码图片）</param>
        /// <param name="version">0</param>
        /// <param name="scale">4</param>
        /// <returns></returns>
        public static byte[] GetBytes(string text, int version, int scale)
        {
            byte[] buffer = null;

            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    // 初始化二维码生成工具
                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    qrCodeEncoder.QRCodeVersion = version;
                    qrCodeEncoder.QRCodeScale = scale;

                    // 将字符串生成二维码图片
                    Bitmap image = qrCodeEncoder.Encode(text, Encoding.Default);

                    // 保存为PNG到内存流
                    using (MemoryStream ms = new MemoryStream())
                    {
                        image.Save(ms, ImageFormat.Png);
                        buffer = ms.GetBuffer();
                    }
                }
                catch { }
            }

            return buffer;
        }
        /// <summary>
        /// 根据服务器的路径获取图片的buffer
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static byte[] GetImageWithQrcode(string text)
        {
            byte[] buffer = null;
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    // 初始化二维码生成工具
                    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    qrCodeEncoder.QRCodeVersion = 0;
                    qrCodeEncoder.QRCodeScale = 7;
                    qrCodeEncoder.QRCodeBackgroundColor = Color.White;

                    // 将字符串生成二维码图片
                    Bitmap map = qrCodeEncoder.Encode(text, Encoding.Default);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        map.Save(ms, ImageFormat.Png);
                        return ms.ToArray();
                    }
                }
                catch { }
            }
            return buffer;
        }

        //保存图片路径（服务器外的路径） 定义一个类作为返回值类型
        public static ImageUrl SaveStreamToPicture(string url)
        {

            byte[] pageData;
            string tempFile = Path.GetTempFileName();
            using (var writer = File.OpenWrite(tempFile))
            {
                var client = new RestClient();
                var request = new RestRequest(url);
                request.ResponseWriter = responseStream =>
                {
                    using (responseStream)
                    {
                        responseStream.CopyTo(writer);
                    }
                };
                pageData = client.DownloadData(request);
            }
            //将二进制流数据转换为图片
            Image image = Image.FromStream(new MemoryStream(pageData));



            Bitmap bmp = new Bitmap(new MemoryStream(pageData));
            string path = "/image/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string fullPath = path + "3.png";

            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))        //如果该方法是静态方法则 Server 前要添加一些东西
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
            }
            // bmp.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);
            // ImgHelper.Compress(bmp, fullPath, 100);




            bmp.Dispose();
            ImageUrl a = new ImageUrl()
            {
                Img = image,
                Url = fullPath
            };
            return a;
        }

        //返回图片和路径
        public static ImageUrl BinaryStreamToPicture(byte[] pageData)
        {
            Image image = Image.FromStream(new MemoryStream(pageData));
            Bitmap bmp = new Bitmap(new MemoryStream(pageData));
            string path = "/image/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string fullPath = path + "2.png";
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))        //如果该方法是静态方法则 Server 前要添加一些东西
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
            }



            // bmp.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);

            ImgHelper.Compress(bmp, fullPath, 100);



            bmp.Dispose();
            ImageUrl a = new ImageUrl()
            {
                Img = image,
                Url = fullPath
            };
            return a;
        }

        //返回本地图片和路径
        public static ImageUrl BinaryToImage(string imgurl, string nickName, string photoimg)
        {
            //加载图片  这个是目标图片
            string imurl = imgurl;
            //将图片转化Graphics  这个是背景图片 
            Image img = new Bitmap(new Bitmap("\\image\\22.jpg"), 765, 1356);//设置背景图片大小   固定的图片路径，不确定是否正确  E:\\HYRD\\heyirunde\\heyirunde
            Graphics g = Graphics.FromImage(img);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//加上抗锯齿效果   

            Point[] destPoints1 = {
                  new Point(635, 1226),//图片左上点
                  new Point(735, 1226),//图片右上点
                  new Point(635, 1326),//图片左下点
                };
            g.DrawImage(new Bitmap(imurl), destPoints1);//按指定的顶点画图
            //图像
            string photoimgs = photoimg;
            Point[] destPoints2 = {
                  new Point(735, 1256),//图片左上点
                  new Point(685, 1256),//图片右上点
                  new Point(735, 1306),//图片左下点
                };
            g.DrawImage(new Bitmap(photoimgs), destPoints2);//按指定的顶点画图

            //定义字体
            System.Drawing.Font font = new Font("宋体", 13, FontStyle.Bold);
            RectangleF textArea = new RectangleF(675, 1230, 80, 26);
            g.DrawString(nickName, font, Brushes.Black, textArea);

            string path = "/image/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string fullPath = path + "1.png";//缺少 6位随机数
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))        //如果该方法是静态方法则 Server 前要添加一些东西
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
            }
            img.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);
            //ImgHelper.Compress(img, fullPath, 100);
            img.Dispose();//显示释放资源l
            g.Dispose();
            ImageUrl a = new ImageUrl()
            {
                Img = img,
                Url = fullPath
            };
            return a;
        }

        //ImageProcessor
        public static ImageUrl SaveImageReturnUrl(string imgurl)
        {
            if (string.IsNullOrEmpty(imgurl))
            {
                throw new ArgumentNullException(imgurl);
            }
            byte[] photoBytes = File.ReadAllBytes(imgurl);
            // 检测格式
            ISupportedImageFormat format = new PngFormat { Quality = 70 };
          //  format.Save("\\image\\33.png",Image.FromStream(new MemoryStream(photoBytes)), 1000);
            Size size = new Size(150, 200);
            Image image;
            string path;
            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // 使用重载初始化ImageFactory以保留EXIF元数据。
                    using (ImageFactory imageFactory = new ImageFactory(true))
                    {
                        // 加载，调整大小，设置格式和质量并保存图像。
                        imageFactory.Load("E:\\HYRD\\heyirunde\\heyirunde\\image\\34.png")
                                    .Resize(size)
                                    .Format(format)
                                    .Save("E:\\HYRD\\heyirunde\\heyirunde\\image\\37.png")
                                   
                                    ;                                  
                        //对获取的imageFactory对象进行对应的操作
                         image = imageFactory.Image;
                         path = imageFactory.ImagePath;
                    }
                    //对获取的数据流进行操作
                }
            }
            ImageUrl imageUrl = new ImageUrl()
            {
                Img = image,
                Url = path
            };
            return imageUrl;
        }

    }
    public class ImageUrl
    {
        public Image Img { get; set; }
        public string Url { get; set; }
    }
}